<template>

    <!--顶部出入库，查询-->
    <div style="margin-bottom: 10px;">
        <el-button type="primary" @click= "AddGoodsClick" style="margin-right: 10px;">新增货品</el-button>
        <el-input v-model="GoodsSearchInput" style="width: 240px" placeholder="按货品编号搜索" :prefix-icon="Search"/>
    </div>

    <!--货品数据展示表格-->
    <el-table :data="GetGoodsData" style="width: 100%; margin-top: 15px;" highlight-current-row>
        <el-table-column fixed prop="goodsID" label="货品编号" align="center"/>
        <el-table-column prop="goodsName" label="货品名称" align="center"/>

        <el-table-column prop="stockStatus" label="库存状态" sortable align="center">
            <template #default="{row}">
                <el-tag :type="getTagType(row.goodsInventory)">
                    {{ getStockStatus(row.goodsInventory) }}
                </el-tag>
            </template>
        </el-table-column>

        <el-table-column prop="goodsInventory" label="库存数量" sortable align="center">
            <template #default="{row}">
                {{ row.goodsInventory }}
            </template>
        </el-table-column>
        <el-table-column prop="goodsSupplierName" label="供应商名称"  align="center"/>
        <el-table-column prop="supplierSupplierID" label="供应商编号"  align="center"/>
        
        <!-- 操作列 -->
        <el-table-column fixed="right" label="操作" width="180" align="center">
            <template #default="{row}">
                <el-button size="small" type="primary" @click="EditGoodsClick(row)">
                    <el-icon><Edit /></el-icon>编辑
                </el-button>
                <el-button 
                    size="small" 
                    type="danger" 
                    @click="DeleteGoodsClick(row)"
                >
                    <el-icon><Delete /></el-icon>删除
                </el-button>
            </template>
        </el-table-column>

        <template #empty>
            <el-empty description="暂无货品数据" />
        </template>
    </el-table>

    <!-- 新增对话框 -->
    <el-dialog v-model="AddGoodsDialog" title="新增货品" width="500">
        <el-form :model="PostGoodsData" label-width="80px" :rules="formRules">
            <el-form-item label="货品名称" prop="goodsName">
                <el-input v-model="PostGoodsData.goodsName" />
            </el-form-item>
            <el-form-item label="初始库存" prop="goodsInventory">
                <el-input-number 
                    v-model="PostGoodsData.goodsInventory" 
                    :min="0" 
                    :precision="0"
                    :step="1"
                />
            </el-form-item>
            <el-form-item label="供应商" prop="supplierSupplierID">
                <el-select 
                    v-model="PostGoodsData.supplierSupplierID" 
                    placeholder="选择供应商"
                    filterable
                    clearable
                >
                    <el-option
                        v-for="item in GetSupplierData"
                        :key="item.supplierId"
                        :label="item.supplierName"
                        :value="item.supplierId"
                    />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="AddGoodsDialog = false">取消</el-button>
                <el-button type="primary" @click="PostGoods">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 编辑对话框 -->
    <el-dialog v-model="EditGoodsDialog" title="修改货品" width="500">
        <el-form :model="PutGoodsData" label-width="80px">
            <el-form-item label="货品名称">
                <el-input v-model="PutGoodsData.goodsName" disabled />
            </el-form-item>
            <el-form-item label="调整库存">
                <el-input-number 
                    v-model="PutGoodsData.goodsInventory" 
                    :min="0" 
                    :precision="0"
                />
            </el-form-item>
            <el-form-item label="供应商">
                <el-select 
                    v-model="PutGoodsData.supplierSupplierID" 
                    placeholder="选择供应商"
                    filterable
                >
                    <el-option
                        v-for="item in GetSupplierData"
                        :key="item.supplierId"
                        :label="item.supplierName"
                        :value="item.supplierId"
                    />
                </el-select>
            </el-form-item>
        </el-form>
        <template #footer>
            <div class="dialog-footer">
                <el-button @click="EditGoodsDialog = false">取消</el-button>
                <el-button type="primary" @click="PutGoods">确定</el-button>
            </div>
        </template>
    </el-dialog>

    <!-- 删除确认对话框 -->
    <el-dialog v-model="DeleteGoodsDialog" title="删除确认" width="400">
        <span>确定删除该货品？</span>
        <p style="color: #666; margin-top: 10px;">{{ currentGoods.goodsName }} (编号: {{ currentGoods.goodsID }})</p>
        <template #footer>
            <el-button @click="DeleteGoodsDialog = false">取消</el-button>
            <el-button type="danger" @click="DeleteGoods">确认删除</el-button>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">

// 导入必要组件
import { reactive, ref, watch, onMounted } from 'vue'
import { Search } from '@element-plus/icons-vue'
import axios from 'axios'
import { ElNotification, ElMessage } from 'element-plus'
import { type Supplier, type GoodsItem } from '@/types'

// 对话框显示参数
let AddGoodsDialog = ref(false)
let EditGoodsDialog = ref(false)
let DeleteGoodsDialog = ref(false)

// 表单验证规则
const formRules = reactive({
    goodsName: [
        { required: true, message: '请输入货品名称', trigger: 'blur' },
        { min: 2, max: 50, message: '货品名称长度在2-50个字符', trigger: 'blur' }
    ],
    goodsInventory: [
        { required: true, message: '请输入初始库存', trigger: 'blur' },
        { type: 'number', message: '库存必须为数字', trigger: 'blur' }
    ],
    supplierSupplierID: [
        { required: true, message: '请选择供应商', trigger: 'change' }
    ]
})

// 库存状态计算
const getStockStatus = (goodsInventory: number) => {
    if (goodsInventory > 100) return '充足'
    if (goodsInventory > 20) return '正常'
    if (goodsInventory > 0) return '紧张'
    return '缺货'
}

// 新增：根据库存数量获取标签类型
const getTagType = (goodsInventory: number) => {
    if (goodsInventory > 100) return 'success'
    if (goodsInventory > 20) return 'info'
    if (goodsInventory > 0) return 'warning'
    return 'danger'
}

// 错误处理
const handleError = (msg: string, error: any) => {
    ElNotification.error({ title: '错误', message: `${msg}: ${error.message}` })
    console.error(msg, error)
}

// 新增：存储全量货品数据
const allGoodsData = ref<GoodsItem[]>([])

// 生命周期钩子，组件挂载后初始化数据
onMounted(async () => {
    await GetSupplier()
    await GetGoods()
})

// 表格单行货品数据
const currentGoods = reactive<GoodsItem>({
    goodsID: 0,
    goodsName: '',
    goodsInventory: 0,
    supplierSupplierID: 0,
    goodsSupplierName: ''
})

// 添加货品回调
function AddGoodsClick(){
    AddGoodsDialog.value = true
}

// 编辑货品回调
function EditGoodsClick(row: GoodsItem){
    Object.assign(PutGoodsData, row)
    EditGoodsDialog.value = true
}

// 删除货品回调
function DeleteGoodsClick(row: GoodsItem){
    Object.assign(currentGoods, row)
    DeleteGoodsDialog.value = true
}

// GET ------------------------------------------ GET //

// GET: 获取的货品数据（修改：改为过滤后的数据）
const GetGoodsData = ref<GoodsItem[]>([])

// GET: 获取的供应商数据
const GetSupplierData = ref<Supplier[]>([])

// GET: 输入商品编号
const GoodsSearchInput = ref('')

// GET: 获取货品数据（修改：存储全量数据并应用过滤）
async function GetGoods(){
    try {
        const res = await axios.get('/api/goods')
        allGoodsData.value = res.data.data || []; // 存储全量数据
        applySearchFilter(); // 应用搜索过滤
    } catch (error) {
        handleError('获取货品失败', error)
    }
}

// 新增：应用搜索过滤函数
function applySearchFilter() {
    const searchValue = GoodsSearchInput.value.trim();
    if (!searchValue) {
        // 无搜索内容时显示全量数据
        GetGoodsData.value = [...allGoodsData.value];
    } else {
        // 基于货品编号进行前端过滤
        GetGoodsData.value = allGoodsData.value.filter(item => 
            String(item.goodsID).includes(searchValue)
        );
    }
}

// 修改：监听搜索输入变化，应用前端过滤（移除原有API请求）
watch(
    GoodsSearchInput, 
    (newVal, oldVal) => {
        applySearchFilter();
    }
)

// 移除原有搜索请求函数
// async function GetGoodsById(){...}

// GET: 获取供应商数据
async function GetSupplier(){
    try {
        const res = await axios.get('/api/supplier')
        GetSupplierData.value = res.data.data
    } catch (error) {
        handleError('获取供应商失败', error)
    }
}

// POST ------------------------------------------ POST //

// POST: 添加的货品数据
const PostGoodsData = reactive({
    goodsName: '',
    goodsInventory: 0,
    supplierSupplierID: null as number | null
})

// POST: 添加货品数据
async function PostGoods(){
    if (!PostGoodsData.goodsName.trim()) {
        ElMessage.error('货品名称不能为空')
        return
    }
    if (PostGoodsData.goodsInventory < 0) {
        ElMessage.error('库存不能为负数')
        return
    }
    if (!PostGoodsData.supplierSupplierID) {
        ElMessage.error('请选择供应商')
        return
    }
    try {
        await axios.post('/api/goods', PostGoodsData)
        ElNotification.success('新增成功')
        AddGoodsDialog.value = false
        PostGoodsData.goodsName = ''
        PostGoodsData.goodsInventory = 0
        PostGoodsData.supplierSupplierID = null
        await GetGoods() // 刷新数据（会重新应用过滤）
    } catch (error) {
        handleError('新增失败', error)
    }
}

// PUT ------------------------------------------ PUT //

// PUT: 修改的货品数据
const PutGoodsData = reactive({
    goodsID: 0,
    goodsName: '',
    goodsInventory: 0,
    supplierSupplierID: 0
})

// PUT: 修改货品数据
async function PutGoods(){
    try {
        await axios.put(`/api/goods/${PutGoodsData.goodsID}`, PutGoodsData)
        ElNotification.success('修改成功')
        EditGoodsDialog.value = false
        await GetGoods() // 刷新数据（会重新应用过滤）
    } catch (error) {
        handleError('修改失败', error)
    }
}

// DELETE ------------------------------------------ DELETE //

// DELETE: 删除货品数据
const DeleteGoods = async () => {
    if (currentGoods.goodsInventory || 0 > 0) {
        ElMessage.error('库存不为0，无法删除')
        return
    }
    try {
        await axios.delete(`/api/goods/${currentGoods.goodsID}`)
        ElNotification.success('删除成功')
        DeleteGoodsDialog.value = false
        await GetGoods() // 刷新数据（会重新应用过滤）
    } catch (error) {
        handleError('删除失败', error)
    }
}

</script>

<style scoped>
.el-table-column {
    text-align: center;
}
</style>